package org.javaboy.demo.jedis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.function.Consumer;

public class RedisClient {

    private final JedisPool jedisPool;

    public RedisClient() {
        // 创建 JedisPoolConfig 对象，设置连接池配置
        GenericObjectPoolConfig<Jedis> config = new GenericObjectPoolConfig<>();
        // 设置最大连接数
        config.setMaxTotal(10);
        // 设置最大空闲连接数
        config.setMaxIdle(5);
        // 设置最大等待时间
        config.setMaxWaitMillis(1000);
        // 设置最小空闲连接数
        config.setMinIdle(2);
        // 获取到 JedisPool 对象
        jedisPool = new JedisPool(config, "centos.javaboy.org", 6379, null, "123");
    }

    public void execute(Consumer<Jedis> consumer) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            consumer.accept(jedis);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }
}
